Client Side Expand/Collapse All Nodes For ASP.NET 2.0 Treeview
Update: This blog has moved to http://pushpontech.blogspot.com
The asp.net treeview provieds a lot of features/functions, one of which is the Expand/Collapse All functionality on the server side. The Treeview Control has got two function for doing just that:
TreeView.ExpandAll(), TreeView.CollapseAll(). But going to server to accomplish such a simple functionality seemed a little odd to me. So, I wrote some javascript to do the same on the client.
Checkout the below script:
function TreeviewExpandCollapseAll(treeViewId, expandAll)
{
var displayState = (expandAll == true ? “none” : “block”);
var treeView = document.getElementById(treeViewId);
if(treeView)
{
var treeLinks = treeView.getElementsByTagName(“a”);
var nodeCount = treeLinks.length;
var flag = true;for(i=0;i<nodeCount;i++)
{
if(treeLinks[i].firstChild.tagName)
{
if(treeLinks[i].firstChild.tagName.toLowerCase() == “img”)
{
var node = treeLinks[i];
var level = parseInt(treeLinks[i].id.substr(treeLinks[i].id.length – 1),10);
var childContainer = GetParentByTagName(“table”, node).nextSibling;if(flag)
{
if(childContainer.style.display == displayState)
{
TreeView_ToggleNode(eval(treeViewId +”_Data”),level,node,’r’,childContainer);
}
flag = false;
}
else
{
if(childContainer.style.display == displayState)
TreeView_ToggleNode(eval(treeViewId +”_Data”),level,node,’l’,childContainer);
}
}
}
}//for loop ends
}
}//utility function to get the container of an element by tagname
function GetParentByTagName(parentTagName, childElementObj)
{
var parent = childElementObj.parentNode;
while(parent.tagName.toLowerCase() != parentTagName.toLowerCase())
{
parent = parent.parentNode;
}
return parent;
}
Get Formatted Version Of Above Script
The above script could be used as:
<a href=”javascript:TreeviewExpandCollapseAll(‘<%=TreeView1.ClientID%>’, true)”>Expand All</a>
<a href=”javascript:TreeviewExpandCollapseAll(‘<%=TreeView1.ClientID%>’, false)”>Collapse All</a>
<asp:TreeView ID=”TreeView1″ …………………
That’s all there is to it.
Hope this is helpful.
pushp
About this entry
You’re currently reading “Client Side Expand/Collapse All Nodes For ASP.NET 2.0 Treeview,” an entry on On .NET, Javascript and more..
- Published:
- June 6, 2007 / 6:07 am
- Category:
- Client Side Programming
- Tags:
3 Comments
Jump to comment form | comment rss [?] | trackback uri [?]